package com.xiaohe.gulimall.interceptor;

import com.xiaohe.common.constant.AuthServerConstant;
import com.xiaohe.common.constant.CartConstant;
import com.xiaohe.common.vo.MemberResponseVo;
import com.xiaohe.gulimall.seckill.vo.UserInfoTo;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * 在执行目标方法之前，判断用户登录状态，并封装传递给controller目标请求
 */
public class CartInterceptor implements HandlerInterceptor {

    public static ThreadLocal<UserInfoTo> toThreadLocal = new ThreadLocal<>();
    //在目标方法执行之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserInfoTo userInfoTo = new UserInfoTo();
        //获取当前登录的信息
        HttpSession session = request.getSession();
        MemberResponseVo member = (MemberResponseVo) session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (member !=null){
            //登录
            userInfoTo.setUserId(member.getId());
        }else {
            //用户未登录登录
            Cookie[] cookies = request.getCookies();
            if(cookies!=null && cookies.length>0){
                for (Cookie cookie : cookies) {
                    String name = cookie.getName();
                    if (name.equals(CartConstant.TEMP_USER_COOKIE_NAME)){
                        userInfoTo.setUserKey(cookie.getValue());
                        userInfoTo.setTemplateUser(true);
                    }
                }
            }
        }
        if(StringUtils.isEmpty(userInfoTo.getUserKey())){
            String uuid = UUID.randomUUID().toString();
            userInfoTo.setUserKey(uuid);
        }
        //目标方法执行之前
        toThreadLocal.set(userInfoTo);
        System.out.println("放入了"+toThreadLocal.get());
        return true;
    }

    //业务执行之后
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserInfoTo userInfoTo = toThreadLocal.get();
        if(!userInfoTo.isTemplateUser()){
            //用户key
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, userInfoTo.getUserKey());
            cookie.setDomain("gulimall.com");
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);
            response.addCookie(cookie);
        }
    }

    //返回本地线性池里面的数据
    public static UserInfoTo getUserInfo(){
        UserInfoTo userInfoTo = toThreadLocal.get();
        System.out.println("userInfoTo---->"+userInfoTo);
        return userInfoTo;
    }
}
